﻿//创建人：Wangjh
//日期：2021-12-15
//描述：派工HTML页面
var page = {
    pagetotal: 0,
    pageSize: 15,
    pageNumber: 1,
    rootPath: getRootPath(), //网站根路径
    //初始化页面
    init: function () {
        page.bind();
        customizedEasyuiPagination('pp'); //定制化分页
        $("#ddlStatus").val("1"); //默认待派工状态
    },
    //页面事件绑定
    bind: function () {
        //主查询结果加载
        $("#gdContainerInfo").datagrid({
            onLoadSuccess: function (data) {
                $('#pp').pagination('refresh', {	// 改变选项，并刷新分页栏信息
                    total: page.pagetotal,
                    pageSize: page.pageSize,
                    pageNumber: page.pageNumber
                });
                customizedEasyuiPagination('pp'); //定制化分页
            },
            onClickRow: function (index, rowData) {

            },
            onSelect: function (index, rowData) {
                //alert('onSelect');
            },
            onCheck: function (index, rowData) {
                var checkedData = $("#gdContainerInfo").datagrid("getChecked");
                if (checkedData.length > 0) {
                    page.searchDataDetail(checkedData);
                }
            },
            onUncheck: function (index, rowData) {
                var checkedData = $("#gdContainerInfo").datagrid("getChecked");
                if (checkedData.length > 0) {
                    page.searchDataDetail(checkedData);
                } else {
                    clearEasyuiDataGrid("gdContainerInfo2", 1);
                }
            },
            onCheckAll: function (index, rowData) {
                var checkedData = $("#gdContainerInfo").datagrid("getChecked");
                if (checkedData.length > 0) {
                    page.searchDataDetail(checkedData);
                }
            },
            onUncheckAll: function (index, rowData) {
                var checkedData = $("#gdContainerInfo").datagrid("getChecked");
                if (checkedData.length > 0) {
                    page.searchDataDetail(checkedData);
                } else {
                    clearEasyuiDataGrid("gdContainerInfo2", 1);
                }
            },
            columns: [[
                 { field: 'ck', title: '选择', checkbox: true },
                 { field: 'MFGORDERNAME', title: '订单号', width: 120 },
		         { field: 'PRODUCTBATCH', title: '件号/批次号', width: 130 },
		         { field: 'PRODUCTDESCRIPTION', title: '零件名称', width: 130 },
                 { field: 'PLANQTY', title: '计划数', width: 40 },
                 { field: 'WIPQTY', title: '在制总数', width: 60 },
                 { field: 'WORKFLOWSTEPNAME', title: '当前工序', width: 180 },
                 { field: 'CONTAINERTYPENAME', title: '流水卡类型', width: 100 },
                 { field: 'PLANNEDSTARTDATE', title: '计划开始', width: 100, formatter: function (value) {
                     if (value !== null) {
                         return value.replace("T", "").replace("00:00:00", "").replace("0:00:00", "");
                     }
                 }
                 },
                 { field: 'PLANNEDCOMPLETIONDATE', title: '计划完成', width: 100, formatter: function (value) {
                     if (value !== null) {
                         return value.replace("T", "").replace("00:00:00", "").replace("0:00:00", "");
                     }
                 }
                 },
		         { field: 'WORKFLOWID', title: '工艺', hidden: true },
                 { field: 'TOGETHERFLAG', title: '批次顺序', hidden: true },
                 { field: 'TOGETHERFLAGNAMES', title: 'TOGETHERFLAGNAMES', hidden: true },
                 { field: 'CONTAINERNAME', title: 'CONTAINERNAME', hidden: true },
                 { field: 'CONTAINERID', title: 'CONTAINERID', hidden: true },
                 { field: 'CONTAINERTYPE', title: '流水卡类型', hidden: true },
                 { field: 'PRODUCTID', title: '零件图号ID', hidden: true },
                 { field: 'PRODUCTNAME', title: '零件图号', hidden: true },
                 { field: 'PRODUCTREV', title: '零件版本', hidden: true },
                 { field: 'WORKFLOWSTEPID', title: '工序ID', hidden: true },
                 { field: 'SEQUENCE', title: 'sequence', hidden: true },
                 { field: 'WORKCENTERNAME', title: 'WORKCENTERNAME', hidden: true },
                 { field: 'WORKCENTERID', title: 'WORKCENTERID', hidden: true }

	           ]]
        });
        //批次号列表加载
        $("#gdContainerInfo2").datagrid({
            onLoadSuccess: function (data) {
                //                if (data.rows.length > 0) {
                //                    $(this).datagrid('checkAll');
                //                    $(this).datagrid('selectRow', 0);
                //                }
            },
            onSelect: function (rowIndex, rowData) {

            },
            columns: [[
                 { field: 'ck', title: '选择', checkbox: true },
		         { field: 'CONTAINERNAME', title: '流水卡号', width: 130 },
                 { field: 'STATUS', title: '状态', width: 60, styler: function cellStyler(value, row, index) {
                     var style = '';
                     switch (value) {
                         case "待派工":
                             style = 'background-color:beige;'
                             break;
                         case "待报工":
                             style = 'background-color:Bisque;'
                             break;
                         case "待检验":
                             style = 'background-color:Yellow;'
                             break;
                         case "待审理":
                             style = 'background-color:Red;'
                             break;
                         case "已转工":
                             style = 'background-color:Aquamarine;'
                             break;
                         case "外委待调度":
                             style = 'background-color:Cyan;'
                             break;

                     }
                     return style;
                 }
                 },
                 { field: 'QTY', title: '在制数', width: 45 },
                 { field: 'TEAMNAME', title: '班组', width: 75 },
                 { field: 'ISHAVESURPASS', title: '超越单', width: 45 },
                 { field: 'CONTAINERID', title: 'CONTAINERID', hidden: true },
                 { field: 'ISHOLD', title: '暂停', hidden: true },
                 { field: 'FACTORYNAME', title: '工厂分区', hidden: true },
                 { field: 'CONTAINERID', title: '批次ID', hidden: true },
                 { field: 'WORKFLOWID', title: '工艺ID', hidden: true }
	           ]]
        });
        //分页事件
        $('#pp').pagination({
            onSelectPage: function (pageNumber, pageSize) {
                customizedEasyuiPagination('pp'); //定制化分页
                page.pageSize = pageSize; page.pageNumber = pageNumber;
                page.searchData();
            }
        });
        //绑定分页go按钮
        $('#pageGo').on("click", function () {
            var pageNumber = $(this).parents('tr').find('.pagination-num').val();
            page.pageNumber = pageNumber;
            page.searchData();
        });
        //查询按钮事件
        $('#btnSearch').on("click", function () {
            page.pageNumber = 1;
            page.searchData();
        });
        //更改事件
        $("#txtScanContainer").textbox({ onChange: function (o, n) {
            page.searchData();
        }
        });
        //更改事件
        $("#txtScanMfgorder").textbox({ onChange: function (o, n) {
            page.searchData();
        }
        });
        //清除按钮
        $('#btnReset').on("click", function () {
            page.reset(true, true);
            page.pageNumber = 1; page.pagetotal = 0
            $('#pp').pagination('refresh', {
                total: page.pagetotal,
                pageSize: page.pageSize,
                pageNumber: page.pageNumber
            });
        });
        //单次派工按钮
        $('#pupStepDispatch').on("click", function () {
            clearMessage();
            page.dispatch("1");
        });
        //批量派工按钮
        $('#puplStepDispatch').on("click", function () {
            clearMessage();
            page.dispatch("2");
        });

        //文档查看按钮
        $('#pupDocumentView').on("click", function () {
            clearMessage();
            page.viewDoc();
        });
        //超越单查看
        $('#pupSurpassInfo').on("click", function () {
            clearMessage();
            page.viewSurpassBill();
        });
        //批次流水卡打印查看
        $('#btnViewContainer').on("click", function () {
            clearMessage();
            page.viewContainerPrint();
        });
    },
    //查询
    searchData: function () {
        page.reset(false, true);
        var gridID = "#gdContainerInfo";
        var param = {
            action: "searchData",
            pageSize: page.pageSize,
            pageNumber: page.pageNumber,
            containerName: $("#txtContainer").textbox('getValue'),
            scanContainerName: $("#txtScanContainer").textbox('getValue'),
            scanMfgorderName: $("#txtScanMfgorder").textbox('getValue'),
            productName: $("#txtProduct").textbox('getValue'),
            specNo: $("#txtSpecNo").textbox('getValue'),
            status: $("#ddlStatus").val()
        };
        $.ajax({
            type: "Post",
            url: page.rootPath + "/Ashx/ContainerStepDispatchHandler.ashx",
            data: param,
            cashe: false,
            async: true,
            beforeSend: function () {
                $(gridID).datagrid('loading');
                $(this).attr("disabled", "disabled"); //禁用按钮
            },
            success: function (data) {
                //console.log(data);
                $(gridID).datagrid('loaded');
                $(this).removeAttr("disabled"); //恢复按钮
                var result = JSON.parse(data);
                if (result.Result) {
                    //给分页对象赋值
                    page.pagetotal = result.RowCount;
                    $(gridID).datagrid('loadData', { total: result.RowCount, rows: result.DBTable });
                } else {
                    displayMessage(result.Message, false);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $(gridID).datagrid('loaded');
                $(this).removeAttr("disabled"); //恢复按钮
                alert(XMLHttpRequest.responseText);
            }
        });
    },
    //查询批次明细
    searchDataDetail: function (rowDatas) {
        clearMessage();
        clearEasyuiDataGrid("gdContainerInfo2", 1);
        var gridID = "#gdContainerInfo2";
        var params = [];

        rowDatas.forEach(function (rowData) {
            var param = {
                status: $("#ddlStatus").val(),
                togatherFlag: rowData.TOGETHERFLAGNAMES,
                productID: rowData.PRODUCTID,
                workflowStepID: rowData.WORKFLOWSTEPID,
                cuWorkCenterID: rowData.WORKCENTERID,
                mfgOrderName: rowData.MFGORDERNAME
            };
            if (isNullOrWhiteSpaceStr(rowData.PLANNEDSTARTDATE) == true) {
                param.plannedStartDate = "";
            } else {
                param.plannedStartDate = rowData.PLANNEDSTARTDATE;
            }
            if (isNullOrWhiteSpaceStr(rowData.PLANNEDCOMPLETIONDATE) == true) {
                param.plannedCompletionDate = "";
            } else {
                param.plannedCompletionDate = rowData.PLANNEDCOMPLETIONDATE;
            }
            if (rowData.CONTAINERTYPE == "7") {
                param.containerType = "7";
            } else {
                param.containerType = "";
            }
            params.push(param);
        });

        var ajaxParam = { action: "getContainerDetails", params: JSON.stringify(params) }

        $.ajax({
            type: "Post",
            url: page.rootPath + "/Ashx/ContainerStepDispatchHandler.ashx",
            data: ajaxParam,
            cashe: false,
            async: true,
            beforeSend: function () {
                $(gridID).datagrid('loading');
            },
            success: function (data) {
                //console.log(data);
                $(gridID).datagrid('loaded');
                var result = JSON.parse(data);
                if (result.Result) {
                    //给分页对象赋值
                    page.pagetotal = result.RowCount;
                    $(gridID).datagrid('loadData', { total: result.RowCount, rows: result.DBTable });
                    //选择所有
                    $(gridID).datagrid('checkAll');
                } else {
                    displayMessage(result.Message, false);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $(gridID).datagrid('loaded');
                alert(XMLHttpRequest.responseText);
            }
        });
    },
    //清除方法，重要！！！
    reset: function (iscondition, isresult) {
        clearMessage();
        if (iscondition) {
            $('#txtScanContainer').textbox('clear');
            $('#txtScanMfgorder').textbox('clear');
            $('#txtProduct').textbox('clear');
            $('#txtContainer').textbox('clear');
            $('#txtSpecNo').textbox('clear');
            $("#ddlStatus").val("1");
        }
        if (isresult) {
            clearEasyuiDataGrid("gdContainerInfo", 1);
            clearEasyuiDataGrid("gdContainerInfo2", 1);
        }
    },
    //派工,批量派工条件:同工艺，同件号,同批次类型，同工序,(同可派数量?) dispatchType: 1、单条派工，2、批量派工，3、工步派工
    dispatch: function (dispatchType) {
        var message = "";
        var url = page.rootPath + '/forms/Custom/YePian/';
        var addr = "";
        var selected = $("#gdContainerInfo2").datagrid("getChecked");
        var orgSelected = $("#gdContainerInfo").datagrid("getChecked");
        if (selected.length == 0) {
            displayMessage("请选择批次", false);
            return;
        }
        if (dispatchType == "1") {//单条派工验证
            if (orgSelected.length > 1) {
                displayMessage("单派工，请选择一条批次", false);
                return;
            }
            addr = "ContainerSingleDispatchFormPage.html";
        }
        if (dispatchType == "2") { //批量派工验证
            var productid = selected[0].PRODUCTID, workflowstepid = selected[0].WORKFLOWSTEPID, containertype = selected[0].CONTAINERTYPE, status = selected[0].STATUS;
            //查询是否有不一样的
            //var selected2= selected.filter(item => (item.PRODUCTID !=productid||item.WORKFLOWSTEPID !=workflowstepid||item.CONTAINERTYPE !=containertype));
            var selected2 = selected.filter(function (item) {
                return item.PRODUCTID != productid || item.WORKFLOWSTEPID != workflowstepid || item.CONTAINERTYPE != containertype || item.STATUS != status;
            });
            if (selected2.length > 0) {
                message = selected2.map(function (item) {
                    return item.CONTAINERNAME;
                }).toString();
                displayMessage("第一个批次与 " + message + "的 件号 或 当前工序 或 批次类型 或状态 不一样", false);
                return;
            }
            addr = "ContainerBatchDispatchFormPage.html";
        }

        if (page.isOper(selected)) {//如果存在暂停，则结束
            return;
        }
        //打开弹出页面
        url += addr + "?v=" + new Date().getTime();
        url += "&parentDiv=dg";
        $('#dg').dialog({
            title: '生产派工',
            width: 1020,
            height: 800,
            top: 10,
            closed: false,
            cache: false,
            modal: true,
            content: '<iframe src="' + url + '" width="100%" height="99%" frameborder="0" scrolling="auto"></iframe>',
            poPupData: selected, //弹出页面的传参
            onClose: function () {
                var returnValue = window.returnValue;
                if (returnValue != null) {
                    if (returnValue.page = "YPContainerDispatchFormPage.html" && returnValue.isSuccess == true) {
                        page.searchData();
                        displayMessage(returnValue.message, true);
                    }
                }
            },
            onOpen: function () {
                $(this).window('hcenter');               
            }
        });

        
    }
    //文档查看
    , viewDoc: function () {
        var selected = $("#gdContainerInfo2").datagrid("getChecked");
        if (selected.length == 0) {
            displayMessage("请选择批次", false);
            return;
        }
        var url = page.rootPath + '/forms/Custom/' + "ProcessDocumentViewPopupForm.aspx?v=" + new Date().getTime();
        url += "&productId=" + selected[0].PRODUCTID + "&workflowId=" + selected[0].WORKFLOWID;
        $('#dg2').dialog({
            title: '文档查看',
            width: 730,
            height: 590,
            top: 10,
            closed: false,
            cache: false,
            modal: true,
            content: '<iframe src="' + url + '" width="100%" height="99%" frameborder="0" scrolling="auto"></iframe>',
            onClose: function () {

            }
        });
    }
    //超越单查看
    , viewSurpassBill: function () {
        var selected = $("#gdContainerInfo2").datagrid("getChecked");
        if (selected.length == 0) {
            displayMessage("请选择批次", false);
            return;
        }
        var url = page.rootPath + '/forms/Custom/' + "SurpassBillPopupForm.aspx?v=" + new Date().getTime();
        var processNo = selected[0].WORKFLOWNAME.replace("WF-", "");
        url += "&ProductName=" + selected[0].PRODUCTNAME + "&ContainerID=" + "'" + selected[0].CONTAINERID + "'" + "&ProcessNo=" + processNo;

        $('#dg3').dialog({
            title: '文档查看',
            width: 850,
            height: 500,
            top: 10,
            closed: false,
            cache: false,
            modal: true,
            content: '<iframe src="' + url + '" width="100%" height="99%" frameborder="0" scrolling="auto"></iframe>',
            onClose: function () {

            }
        });

    }

    //预览批次打印页面 add by zhangrj 2022-03-08
    , viewContainerPrint: function () {
        var selected = $("#gdContainerInfo2").datagrid("getChecked");
        if (selected.length == 0) {
            displayMessage("请选择批次", false);
            return;
        }
        $.ajax({
            type: "Post",
            url: page.rootPath + "/Ashx/CommonHandler.ashx",
            data: { action: "viewPrintPage", params: JSON.stringify(selected) },
            cashe: false,
            async: true,
            success: function (data) {
                var result = JSON.parse(data);
                if (result.Result) {
                    var url = result.ReturnData + "?v=" + new Date().getTime();
                    window.open(url);
                } else {
                    displayMessage(result.Message, false);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest.responseText);
            }
        });
    }
    //验证是否有暂停批次 add by zhangrj 2022-04-18
    , isOper: function (selectedRows) {
        var isvaild = false;
        var param = [];
        for (var i = 0; i < selectedRows.length; i++) {
            param.push({ containerId: selectedRows[i].CONTAINERID, containerName: selectedRows[i].CONTAINERNAME });
        }
        $.ajax({
            type: "Post",
            url: page.rootPath + "/Ashx/CommonHandler.ashx",
            data: { action: "GetOperReason", params: JSON.stringify(param) },
            cashe: false,
            async: false,
            dataType: "json",
            beforeSend: function () {
                $.messager.progress({ text: '', msg: '处理中...' });
            },
            success: function (data) {
                $.messager.progress('close');
                if (data.Result === false) {
                    isvaild = true;
                    displayMessage(data.Message, data.Result);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.messager.progress('close');
                isvaild = true;
                alert(XMLHttpRequest.responseText);
            }
        });
        return isvaild;
    }
}
$(function () {
    page.init();
});